package com.netty.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    //构造器, 完成初始化工作
    public GroupChatClient() throws IOException {
        //获取selector
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST,PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        ////得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("用户:"+username+"已就绪!");
    }

    //向服务器发送消息
    public void sendMsg(String msg){
        msg = username + "发来:"+msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取从服务器端回复的消息
    public void readMsg(){
        try {
            int selectChannelNum = selector.select();//获取selector中的所有注册的通道通道的数量
            if (selectChannelNum>0) {
                //获取所有selectedKeys
                // (就是说获取正在发生事件的channel的对应的selectionKey)
                Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                //检查是否有SelectionKey
                while (keyIterator.hasNext()) {
                    SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isReadable()) {
                        //得到相关的通道
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        //得到一个Buffer
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        //读取到byteBuffer
                        channel.read(byteBuffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(byteBuffer.array());
                        System.out.println(msg.trim());
                    }
                    keyIterator.remove(); //删除当前的selectionKey, 防止重复操作
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        //启动我们客户端
        GroupChatClient groupChatClient = new GroupChatClient();
        //启动一个线程, 每隔3秒，读取从服务器发送数据
        new Thread() {
            public void run(){
                while (true){
                    groupChatClient.readMsg();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String msg = scanner.nextLine();
            groupChatClient.sendMsg(msg);
        }
    }
}
